package com.yc.vcode.web;

import com.yc.vcode.bean.Result;
import com.yc.vcode.bean.VcodeProperties;
import com.yc.vcode.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
@RequestMapping("vcode")
public class VcodeDo {

    // 图片验证码
    @RequestMapping(path = "image",
            produces = MediaType.IMAGE_PNG_VALUE)
    public void imageVcode(HttpSession session,
                           HttpServletResponse response) throws IOException {
        int x = (int) (Math.random() * 9 + 1);
        int y = (int) (Math.random() * 9 + 1);
        String s = x + "x =" + (x * y);
        session.setAttribute("vcode", "" + y);
        // 设值超时时间
        session.setAttribute("vcodeTimeout",
                System.currentTimeMillis() + vcodeProperties.getTimeout() * 1000);
        VerifyCodeUtils.outputImage(200, 80, s, response);
    }

    @Resource
    VcodeProperties vcodeProperties;

    @Resource
    JavaMailSender mailSender;
    @Value("${vcode.fromEmail}")
    private String from;

    // 邮箱验证码
    @RequestMapping(path = "email")
    public Result emailVcode(HttpSession session,
                             String msg,
                             String email) {
        String time = "" + System.currentTimeMillis();
        // 截取后四位
        time = time.substring(time.length() - 4);
        session.setAttribute("vcode", time);
        // 设值超时时间
        session.setAttribute("vcodeTimeout",
                System.currentTimeMillis() + vcodeProperties.getTimeout() * 1000);

        // 构建短信内容
        String msgContent = vcodeProperties.getMsgs().get(msg);
        // 拼接短信验证码
        msgContent = String.format(msgContent, time);

        // 发送邮件
        sendHtmlMail(email, "授权验证码", msgContent);

        return new Result(1, "验证码发送成功!", null);
    }

    public void sendHtmlMail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(from);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(message);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

